<template>
 <div class="borrower">
      
      <el-card class="box-card" shadow="never" style="border:0px;">
        <el-button style="float:right;margin-right:18%;" type="primary" size="mini" v-if="defaultChangeValue!='detail'" @click="createBorrowerDraft" >保存草稿</el-button> 
        
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="right" label-width="100px" style="width: 600px; margin-left:50px;">
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="dataForm.realName"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNo">
          <el-input :disabled="disabledFlag" v-model="dataForm.idCardNo" @change="go"/>
          <!-- <span v-if="showError" style="font-size:12px;color:red;">该客户在系统中有拒件的记录，<a @click="rejectLook">前往查看></a></span> -->
          <el-alert v-if="showError" :closable="false" type="warning" show-icon>该客户在系统中有拒件的记录， <el-link @click="rejectLook" style="margin-top:-3px;" type="danger">前往查看</el-link></el-alert>
        </el-form-item>
         <el-form-item label="民族" prop="national">
           <DicSelect dictType = "民族" :dictValue="dataForm.national" v-on:dictValue="dataForm.national=$event"/>
        </el-form-item>
         <el-form-item label="婚姻情况" prop="marriageStatus">
          <DicSelect dictType = "婚姻情况" :dictValue="dataForm.marriageStatus" v-on:dictValue="dataForm.marriageStatus=$event"/>
        </el-form-item>
        <el-form-item label="工作单位" prop="workCompany">
          <el-input v-model="dataForm.workCompany"/>
        </el-form-item>
        <el-form-item label="岗位/职务" prop="position">
          <el-input v-model="dataForm.position"/>
        </el-form-item>
        <el-form-item label="工作地址" prop="workAddress">
          <el-input v-model="dataForm.workAddress"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
           <el-radio-group  v-model="dataForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
         </el-radio-group>
        </el-form-item>
          <el-form-item label="年龄" prop="age">
          <el-input @change="focusAge" type="number" v-model="dataForm.age">
            <template slot="append">岁</template>
          </el-input>
          <!-- <span v-if="showAgeError" style="font-size:11px;color:red;">年龄不符合产品政策</span> -->
          <el-alert v-if="showAgeError" :closable="false" type="warning" show-icon>年龄不符合产品政策 </el-alert>
        </el-form-item>
         <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="dataForm.mobile"/>
        </el-form-item>
         <el-form-item label="现居住地址" prop="liveAddress">
          <el-input v-model="dataForm.liveAddress"/>
        </el-form-item>
        <el-form-item label="户籍所在地" prop="householdAddress">
          <el-input v-model="dataForm.householdAddress"/>
        </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="dataForm.email"/>
        </el-form-item>
          <el-form-item label="家庭成员数" prop="famliyNum">
          <el-input type="number" v-model="dataForm.famliyNum"/>
        </el-form-item>
          <el-form-item label="银行卡号码" prop="bankCard">
          <el-input v-model="dataForm.bankCard"/>
        </el-form-item>
       
       
      </el-form>
      </el-card>

      <el-card class="box-card" shadow="never" style="border:0px;">
    <el-form :model="formData3"  ref="formData3" status-icon label-position="right" label-width="90px" style="width: 600px; margin-left:50px;" >
      <el-row
        v-for="(item,index) in formData3.powerAttrList"
        :key="item.key"  
        style="border-bottom: 1px solid #f0f0f0;padding: 10px;"
      >
        <el-form-item
          label="关系"
          :prop="'powerAttrList.' + index + '.relation'"
          :rules="[{ required: true, message: '关系不能为空',trigger: 'change'}]"
        >
          <DicSelect dictType = "与借款人关系" :dictValue="item.relation" v-on:dictValue="item.relation=$event"/>
        </el-form-item>
         <el-form-item
          label="姓名"
          :prop="'powerAttrList.' + index + '.realName'"
          :rules="[{ required: true, message: '请输入姓名',trigger: 'change'}]"
        >
          <el-input v-model="item.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item
          label="联系电话"
          :prop="'powerAttrList.' + index + '.mobile'"
          :rules="[{ required: true, message: '请输入联系电话',trigger: 'blur'},
          { required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的联系电话', trigger: ['blur'] }]"
        >
          <el-input v-model="item.mobile" autocomplete="off" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item style="float:right;"><!--v-if="index >2"-->
           <el-button type="danger"  size="medium" @click="removeRow(index)" >删除</el-button>
        </el-form-item>
      </el-row>
      <el-row style="margin-top:10px;">
        <span style="font-size:18px;margin:5px;">添加联系人</span>
        <el-button icon="el-icon-plus" @click="addRow"></el-button>
      </el-row>
    </el-form>
      <div style="width:150px;height:40px;margin-left:20%;margin-top:5%;">
        <el-button type="warning" v-if="defaultChangeValue === 'detail'" @click="createData" style="width:150px;height:40px;">保存</el-button>
        <el-button type="warning" v-else @click="createData" style="width:150px;height:40px;">下一步</el-button>
      </div>
        
  </el-card>
 
  </div>
</template>


<script>
import { getAgeAndSex } from '@/utils/validate';
import { createBorrower,createBorrowerDraft,getByIdCardNo ,findByProjectId, updateBorrower,findRejectRecordByCardNo} from '@/api/borrower'
import DicSelect from '@/components/select'

export default {
  name: 'borrower',
  components: { DicSelect },
  // 接受父组件的值
  props: {
     changeValue: undefined,
     projectId: undefined,
     submitProjectId: undefined,
     operation: undefined
    },
  data() {
    return {
      updateParam: undefined,
      listLoading: true,
      options:[],
      nation: undefined,
      value:undefined,
       list: undefined,
      total: 0,
      idCardNo: undefined,
      showError: false,
      showAgeError: false,
      defaultProjectId: undefined,
      disabledFlag: false,
      projectIdByDraw: undefined,
      defaultChangeValue: this.changeValue,
      listQuery: {
        page: 1,
        limit: 20,
        pid: undefined,
        categoryName: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        realName: undefined,
        idCardNo: undefined,
        type: 1,
        national: undefined,
        marriageStatus: undefined,
        workCompany: undefined,
        position: undefined,
        workAddress: undefined,
        sex: undefined,
        age: undefined,
        mobile: undefined,
        liveAddress: undefined,
        householdAddress: undefined,
        email: undefined,
        famliyNum: undefined,
        bankCard: undefined,
        clientFamliys: []
        
      },
      dialogFormVisible: false,
      dialogStatus: '',
      data: [{
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      formData3: {
        powerAttrList: [
          // {
          //   realName: "",
          //   relation: "",
          //   mobile: "",
          // },
          // {
          //   realName: "",
          //   relation: "",
          //   mobile: "",
          // },
          // {
          //   realName: "",
          //   relation: "",
          //   mobile: "",
          // },
        ]
      },
      rules: {
        realName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        idCardNo: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { required: true, pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: ['blur'] }
        ],
        // national: [
        //   { required: true, message: '请选择民族', trigger: 'change' }
        // ],
        // marriageStatus: [
        //   { required: true, message: '请选择婚姻情况', trigger: 'change' }
        // ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { required: true, pattern: /^((13[0-9])|(14[579])|(15[0-35-9])|(16[2567])|(17[0-35-8])|(18[0-9])|(19[0-35-9]))\d{8}$/, message: '请输入正确的手机号', trigger: ['blur'] }],
        // liveAddress: [
        //   { required: true, message: '请输入居住地址', trigger: 'blur' }
        // ],
        // householdAddress: [
        //   { required: true, message: '请输入户籍所在地', trigger: 'blur' }
        // ],
        // email: [
        //   { required: true, message: '请输入电子邮箱', trigger: 'blur' },
        //   { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }
        // ],
        // famliyNum: [
        //   { required: true, message: '请输入家庭成员人数', trigger: 'blur' }
        // ],
        // bankCard: [
        //   { required: true, message: '请输入银行卡号码', trigger: 'blur' },
        //   { required: true, min:16,max:19, message: '请输入正确的银行卡号码', trigger: ['blur'] }
        // ]
      },
      downloadLoading: false
    }
  },
  watch: {
    "changeValue":function(val){
      this.defaultChangeValue = val
    }
  },
  computed: {
  },
  created() {
    // var form = localStorage.getItem("borrower")
    // if(form!= undefined){
    //   this.dataForm = JSON.parse(form)
    //   this.formData3.powerAttrList = this.dataForm.clientFamliys
    // }
    let isBack = localStorage.getItem("isBack")//标识是从共款人上一步回来借款人页面的 可以用身份证进行查询
    console.log(111)
    if( this.operation === 'add' ) {
      isBack = 'false'

    }
    let backIdCardNo = localStorage.getItem("backIdCardNo")
    let projectIdByDraw1 = localStorage.getItem("projectIdByDraw")
    if( this.operation === 'add' && projectIdByDraw1!=undefined && projectIdByDraw1!='undefined'){
      this.idCardNo = backIdCardNo
      this.getBorrowerInfo(this.idCardNo)
    }
  
   if( this.operation === 'edit'){
      //草稿状态 从列表进件列表进来
    let idCardNoQuery = this.$route.query.idCardNo
    let projectIdByDraw = this.$route.query.projectIdByDraw
    if( idCardNoQuery != undefined ) {
      this.idCardNo = idCardNoQuery
      this.projectIdByDraw = projectIdByDraw
      this.getBorrowerInfo(this.idCardNo)
    }
   }
   if( (this.operation !='add' && this.operation !='edit') || isBack === 'true') { //不是新增进件页面进来才取值回填
   console.log("111111111111111111111111111111,{}",this.operation)
         //进入提交进件页面就把之前存储的项目ID 借款人ID缓存清除
    //回填信息
    if( this.defaultChangeValue === 'detail'){
      var idCardNo = localStorage.getItem("idCardNo")
      this.getBorrowerInfo(idCardNo)
    }else{
      localStorage.setItem("projectId",undefined)
      localStorage.setItem("borrowerId",undefined)
      localStorage.setItem("idCardNo",undefined)
    }
    //编辑页面进来
    if( this.projectId != undefined) {
      this.defaultProjectId = this.projectId
      this.findByProjectId()
      this.defaultChangeValue = "detail"
    }
    //重新提交页面进来
    if( this.submitProjectId != undefined) {
      this.defaultProjectId = this.submitProjectId
      this.findByProjectId()
    }
    //上一步回填信息
    
    if( (backIdCardNo != 'undefined' || backIdCardNo != undefined) && this.defaultProjectId === undefined ) {
       this.idCardNo = backIdCardNo
       this.getBorrowerInfo(this.idCardNo)
      //  let isBack = localStorage.getItem("isBack",true)//标识是从共款人上一步过去借款人页面的  不删除身份证
      //  if( !isBack ) {
      //     localStorage.setItem("backIdCardNo",undefined)
      //  }
    }

   }
  },
  methods: {
    addRow() {
      this.formData3.powerAttrList.push({
        realName: "",
        relation: "",
        mobile: "",
        key: Date.now() // 更改前没有
      });
    },
    rejectLook(){
      this.$router.push("/task/rejectList")
    },
    // 删除属性列
    removeRow(index) {
      this.formData3.powerAttrList.splice(index, 1);
    },
    // 提交
    submit(formName) {
      this.$refs[formName].validate(valid => {
        console.log(this.formData3);
        if (valid) {
          alert("submit!");
        } else {
          return false;
        }
      });
    },
    next() {
    if (this.active++ > 5) this.active = 0;
      },
     findByProjectId() {
      this.listLoading = true
      findByProjectId({projectId:this.defaultProjectId})
        .then(response => {
          if(response.data != undefined ) {
            this.disabledFlag = true
            this.dataForm = response.data
            this.dataForm.projectId = this.defaultProjectId
          this.dataForm.sex = ""+this.dataForm.sex+""
          this.formData3.powerAttrList = this.dataForm.clientFamliys
          console.log(this.dataForm)
          }
        })
        .catch(() => {
          this.resetForm()
        })
    },
     getBorrowerInfo(idCardNo) {
      if( idCardNo == undefined || idCardNo === 'undefined' ) {
        return false
      }
      this.listLoading = true
      getByIdCardNo({idCardNo:idCardNo,projectId: this.projectIdByDraw})
        .then(response => {
          console.log(response.data)
          if(response.data != undefined ) {
            this.disabledFlag = true
            this.dataForm = response.data
            if( this.projectIdByDraw != undefined) {
              this.dataForm.projectId = this.projectIdByDraw
            }
          this.dataForm.sex = ""+this.dataForm.sex+""
          if( this.dataForm.clientFamliys != undefined ) {
          this.formData3.powerAttrList = this.dataForm.clientFamliys
          for( let i = 0;i < this.formData3.powerAttrList.length;i++){
            if(this.formData3.powerAttrList[i].relation === undefined ) {
              this.formData3.powerAttrList[i].relation=i+1
            }
          }
          }
          console.log(this.dataForm)
          }
        })
        .catch((e) => {
          console.log(e)
          this.resetForm()
        })
    },
     findRejectRecordByCardNo(idCardNo) {
      findRejectRecordByCardNo({idCardNo:idCardNo})
        .then(response => {
          console.log(response)
           if( response.total > 0) {
             this.showError = true
           }else{
             this.getBorrowerInfo(idCardNo)
           }
        })
        .catch(() => {
        })
    },
    resetForm() {
      this.dataForm = {
       realName: undefined,
        idCardNo: undefined,
        type: 1,
        national: undefined,
        marriageStatus: undefined,
        workCompany: undefined,
        position: undefined,
        workAddress: undefined,
        sex: undefined,
        age: undefined,
        mobile: undefined,
        liveAddress: undefined,
        householdAddress: undefined,
        email: undefined,
        famliyNum: undefined,
        bankCard: undefined
      }
    },
      // 实现自动生成生日，性别，年龄
      go(val) {
        //校验是否有拒件记录
        if(val != undefined ) {
          this.findRejectRecordByCardNo(val)
          // console.log(this.showError)
          // if( this.showError === true) {
          //    this.getBorrowerInfo(val)
          // }
        }
        let borrower = getAgeAndSex(val)
        this.dataForm.sex = borrower.sex;//性别
        this.dataForm.age = borrower.age;//年龄
        if(this.dataForm.age > 60 || this.dataForm.age < 18 ) {
          this.showAgeError = true
        }else{
          this.showAgeError = false
        }
        
      },
      focusAge(){
        console.log(11)
          if(this.dataForm.age > 60 || this.dataForm.age < 18 ) {
          this.showAgeError = true
        }else{
          this.showAgeError = false
        }
      },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadPicUrl: function(response) {
      this.dataForm.picUrl = response.data.url
    },
    createData() {
      //  if( this.changeValue != 'detail' ) {
      //       this.$emit("stepChanged",2)
      //      }
      this.dataForm.clientFamliys = this.formData3.powerAttrList
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
           //校验家庭成员
             this.$refs['formData3'].validate(valid => {
               console.log(this.formData3);
              if (valid) {
                   let requestMethod = localStorage.getItem("requestMethod");
                   localStorage.setItem("backIdCardNo",this.dataForm.idCardNo)
                   localStorage.setItem("isBack",false)
                   console.log(this.idCardNo)
                  //  if(this.defaultProjectId == undefined || (this.idCardNo != undefined && requestMethod === 'add')) {
                  //       this.createBorrower()
                  //  }else{
                  //       this.updateBorrower()
                  //  }
                  if( this.operation === 'add'){
                    this.disabledFlag = false //从提交进件进来只能调用新增接口
                  }
                  if( this.disabledFlag ) {
                    this.updateBorrower()
                  }else{
                    this.createBorrower() 
                  }
                  

                  }
                });
          
        }
      })
    },
    createBorrowerDraft(){
          if(this.dataForm.idCardNo === undefined ) {
             this.$message.error("保存草稿也必须填写身份证号哦，方便下次进件回填信息")
             return false
          }
          if(this.dataForm.national === undefined || this.dataForm.national === 0) {
             this.$message.error("保存草稿也必须选择民族哦")
             return false
          }
          this.dataForm.clientFamliys = this.formData3.powerAttrList
          createBorrowerDraft(this.dataForm)
           .then(response => {
             console.log(response.data.id)
             localStorage.setItem("borrowerId",response.data.id)
            //  localStorage.setItem("borrower",JSON.stringify(this.dataForm))
             this.$router.push("/project/index")
             this.$notify.success({
              title: '成功',
              message: '草稿保存成功'
               })
             })
              .catch(response => {
                })         
    },
    createBorrower(){
          createBorrower(this.dataForm)
           .then(response => {
             console.log(response.data.id)
             localStorage.setItem("borrowerId",response.data.id)
            //  localStorage.setItem("borrower",JSON.stringify(this.dataForm))
             
             this.$notify.success({
              title: '成功',
              message: '保存成功'
               })
               if( this.defaultChangeValue != 'detail' ) {
                   this.$emit("stepChanged",2)
                  }else{
                    this.$emit('getCapital')
                  }
             })
              .catch(response => {
                })         
    },
    updateBorrower(){
          updateBorrower(this.dataForm)
           .then(response => {
             localStorage.setItem("borrowerId",this.dataForm.id)
            //  localStorage.setItem("borrower",JSON.stringify(this.dataForm))
             console.log(this.dataForm)
             this.$notify.success({
              title: '成功',
              message: '修改成功'
               })
               if( this.defaultChangeValue != 'detail' ) {
                   this.$emit("stepChanged",2)
                  }else{
                    this.$emit('getCapital')
                  }
             })
              .catch(response => {
                })         
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
  }
}
</script>
